#include "StdAfx.h"
#include "ModulatorImpl.h"
//#include "Statistics.h"
#include "StopConsonantAnalyzer.h"

ModulatorImpl::ModulatorImpl(void)
{
}

ModulatorImpl::~ModulatorImpl(void)
{
}


void PopulateSampleWithMarkers(SampleWithMarkers& sampleWithMarkers, short* sample, unsigned int length, std::vector<SampleMarker>* incomingMarkers)
{
	std::vector<short> tmpSample;
	for(unsigned int i=0; i<length; i++)
	{
		tmpSample.push_back(sample[i]);
	}	
	std::vector<SampleMarker> tmpMarkers;
	if(incomingMarkers)
	{
		for(unsigned int i=0; i<incomingMarkers->size(); i++)
		{
			tmpMarkers.push_back(incomingMarkers->at(i));
		}		
	}
	StopConsonantAnalyzer analyzer;
	analyzer.MarkStopConsonants(sample, length, tmpMarkers);
	
	sampleWithMarkers.first = tmpSample;
	sampleWithMarkers.second = tmpMarkers;
}

void ModulatorImpl::SetSample(short* sample, unsigned int length, std::vector<SampleMarker>* incomingMarkers)
{
	SampleWithMarkers sampleWithMarkers;
	PopulateSampleWithMarkers(sampleWithMarkers, sample, length, incomingMarkers);

	std::list<SampleWithMarkers> tmpList;
	tmpList.push_back(sampleWithMarkers);
	curIdx = 0;
	samples.swap(tmpList);	
}

void ModulatorImpl::AddSample(short* sample, unsigned int length, std::vector<SampleMarker>* incomingMarkers)
{
	SampleWithMarkers sampleWithMarkers;
	PopulateSampleWithMarkers(sampleWithMarkers, sample, length, incomingMarkers);
	samples.push_back(sampleWithMarkers);
}


bool ModulatorImpl::NextModulatorSample(short* output, unsigned int length, std::vector<SampleMarker>* markersReceiver)
{
	if(samples.size()==0)
		return false;

	//SampleWithMarkers curSample = samples.begin();
	if(markersReceiver)
	{
		//copy with correct indices from myMarkers to markersReceiver
		SampleMarker::GetRegion(curIdx, curIdx+length-1, samples.begin()->second, *markersReceiver);
	}
	
	bool retval = true;
	unsigned int outputIdx = 0;
	while(outputIdx<length-1 && samples.size()>0)
	{
		std::vector<short> curSample = samples.begin()->first;
		for(; curIdx<curSample.size() && outputIdx<length; curIdx++, outputIdx++)
		{
			output[outputIdx] = curSample[curIdx];
		}
		if(outputIdx<length-1)
		{
			samples.pop_front();
		}
	}

	if(outputIdx<length-1)
	{
		//not enough material available
		retval = false;
		for(; outputIdx<length; outputIdx++)
		{
			output[outputIdx] = 0;//fill with silence
		}
	}

	return retval;
}
